package Day020_NIO_AIO.demo1_Selector选择器.Test2_Selector常用方法;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * @author zhangyan
 * @date 2020/5/13 9:37
 */
public class Test3_多个Channel注册到一个服务器 {
    public static void main(String[] args) throws Exception{

        //创建3个通道，同时监听3个端口
        //获取ServerSocketChannel对象
        ServerSocketChannel channel1 = ServerSocketChannel.open();
        //设置非阻塞
        channel1.configureBlocking(false);
        //绑定端口号
        channel1.bind(new InetSocketAddress(7777));

        ServerSocketChannel channel2 = ServerSocketChannel.open();
        channel2.configureBlocking(false);
        channel2.bind(new InetSocketAddress(8888));

        ServerSocketChannel channel3 = ServerSocketChannel.open();
        channel3.configureBlocking(false);
        channel3.bind(new InetSocketAddress(9999));

        //获取选择器
        Selector selector = Selector.open();

        //把服务器通道的accept()交给选择器处理
        //注册Channel到Selector
        channel1.register(selector, SelectionKey.OP_ACCEPT);
        channel2.register(selector, SelectionKey.OP_ACCEPT);
        channel3.register(selector, SelectionKey.OP_ACCEPT);
    }
}
